﻿#region Copyright and License Notice
// Copyright (C)2010-2016 - Rob Levine and other contributors
// http://configgen.codeplex.com
// 
// This file is part of ConfigGen.
// 
// ConfigGen is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// ConfigGen is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License and 
// the GNU Lesser General Public License along with ConfigGen.  
// If not, see <http://www.gnu.org/licenses/>
#endregion

using System.IO;
using ConfigGen.Core.ConfigurationSettings;
using ConfigGen.Utilities.Extensions.System;

namespace ConfigGen.Core
{
    /// <summary>
    /// Generates configuration file names for the <see cref="FileOutputWriter"/>.
    /// </summary>
    public class ConfigFileNameGenerator
    {
        /// <summary>
        /// Generates and returns a filename based on the supplied settings.
        /// </summary>
        /// <param name="machineConfiguration">Machine settings for the configuration file being generated</param>
        /// <param name="settings">ConfigGen settings</param>
        /// <returns>Full path filename for generated file</returns>
        public virtual string GenerateFilename(MachineConfigurationSettings machineConfiguration, Preferences settings)
        {
            var outputDirectory = new DirectoryInfo(settings.OutputDirectory);

            if (!settings.FlatDirectoryOutput)
            {
                outputDirectory = new DirectoryInfo(Path.Combine(outputDirectory.FullName, machineConfiguration.MachineName));
            }

            var configFilePath = Path.Combine(outputDirectory.FullName, machineConfiguration.ConfigFilePath);

            if (!settings.ForcedFilename.IsNullOrEmpty())
            {
                // filename has been overridden. Remember that configFileName itself may contain a relative file path (there is no
                // restriction in place saying it must only be a filename), so we need to preserve this.
                configFilePath = Path.Combine(new FileInfo(configFilePath).DirectoryName, settings.ForcedFilename);
            }

            if (settings.MachineSuffix)
            {
                configFilePath += "." + machineConfiguration.MachineName;
            }

            return configFilePath;
        }
    }
}